package cn.mofuxiong.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Moblie_VerityCode extends ActionSupport {
	private static final long serialVersionUID = 1L;
	HttpServletRequest req = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	

	@Override
	public String execute() throws Exception 
	{
		 String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
			
			int mobile_code = (int)((Math.random()*9+1)*100000); //获取随机数
			
			String account = "C26936449"; //查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
			String password = "177f0da5a82d3642af22a1c784e3fcd1";  //查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
			String mobile = req.getParameter("mobile");
			System.out.println("shoujiis : "+mobile);
			String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
			
		
			System.out.println("验证码是 : "+content);
			req.getSession().setAttribute("verifycode", content);
			
			try {
			
				URL url = new URL(postUrl);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setDoOutput(true);//允许连接提交信息
				connection.setRequestMethod("POST");//网页提交方式“GET”、“POST”
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				connection.setRequestProperty("Connection", "Keep-Alive");
				StringBuffer sb = new StringBuffer();
				sb.append("account="+account);
				sb.append("&password="+password);
				sb.append("&mobile="+mobile);
				sb.append("&content="+content);
				OutputStream os = connection.getOutputStream();
				os.write(sb.toString().getBytes());
				os.close();
			
				String line, result = "";
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				while ((line = in.readLine()) != null) 
				{
					result += line + "\n";
				}
				in.close();
				System.out.println(result);
			
				
								
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html; charset=utf-8");
				
				PrintWriter pw = response.getWriter();
				pw.write("{\"p\":\"1\"}");
				
			} 
			catch (IOException e) 
			{
				e.printStackTrace(System.out);
			}
			return null;
			
	}
	
	
	

}
